/**
 * Copyright (C) 2011-2012 Luca Li Greci
 *
 * This file is part of pojo-creator
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pojocreator.utility;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.pojocreator.provider.DataProvider;

/**
 * Helper to access an object through reflection. This class contains the core
 * method to set or retrieve class information.
 * 
 * @author Luca Li Greci
 */
public final class ReflectionHelper {
    private static final SetterInvoker INVOKER = new SetterInvoker();

    private ReflectionHelper() {
    }

    /**
     * Return the generic data type used in a Collection of elements.
     * <p>
     * For instance, for a List of String defined as
     * 
     * <pre>
     * List &lt; String &gt; property;
     * </pre>
     * 
     * the return type of this function is String.class
     * <p>
     * 
     * @param field Field to access
     * @return the class type used in the collection.
     */
    public static Class < ? > collectionOf(final Field field) {
        Type genericFieldType = field.getGenericType();
        if (!(genericFieldType instanceof ParameterizedType)) {
            return null;
        }
        Class < ? > out = null;
        ParameterizedType aType = (ParameterizedType) genericFieldType;
        Type[] fieldArgTypes = aType.getActualTypeArguments();
        for (Type fieldArgType : fieldArgTypes) {
            out = (Class < ? >) fieldArgType;
            break;
        }
        return out;
    }

    /**
     * Set the given {@link Field} in the object with the propertyValue
     * 
     * @param field Field to set
     * @param object Object to set
     * @param value Property's value.
     * @param <S> propertyValue data type.
     * @throws IllegalAccessException in case of error.
     */
    @SuppressWarnings("unchecked")
    public static < S > void set(Field field, Object object, S value) throws IllegalAccessException {
        S objectValue = value;
        if (value instanceof DataProvider < ? >) {
            objectValue = ((DataProvider < S >) value).data();
        }
        INVOKER.invoke(field, object, objectValue);
    }

}
